package com.qf.service.impl;

import com.qf.api.CacheFeign;
import com.qf.constant.CacheConstants;
import com.qf.constant.StrategyConstants;
import com.qf.model.StandardSubmit;
import com.qf.service.StrategyService;
import com.qf.util.PushMsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;

import java.io.IOException;
import java.io.StringReader;

/**
 * 敏感词策略
 *
 * @Author ztf
 * @Date 19:45 2021/11/24
 **/
@Service(value = "dirtyWords")
@Slf4j
public class DirtyWordServiceImpl implements StrategyService {

    @Autowired
    private CacheFeign cacheFeign;

    @Autowired
    private PushMsgUtil pushMsgUtil;

    /**
     * 策略方法
     *
     * @param standardSubmit
     * @return
     */
    @Override
    public boolean execute(StandardSubmit standardSubmit) throws IOException {
        log.info("【策略模块-敏感词策略】开始执行，短信对象内容为：standardSubmit={}", standardSubmit);

        //获取短信发送内容
        String messageContent = standardSubmit.getMessageContent();
        if (messageContent == null || messageContent.length() == 0) {
            log.info("【策略模块-敏感词策略】执行失败，短信内容为空，短信对象内容为：standardSubmit={}", standardSubmit);
            pushMsgUtil.pushReport(standardSubmit, StrategyConstants.STRATEGY_ERROR_DIRTY_WORDS);
            pushMsgUtil.sendLog(standardSubmit, StrategyConstants.STRATEGY_ERROR_DIRTY_WORDS);
            return false;
        }
        //对短信内容进行分词
        StringReader stringReader = new StringReader(messageContent);
        IKSegmenter ikSegmenter = new IKSegmenter(stringReader, true);
        //遍历分词出来的词汇

        Lexeme lexeme = null;
        while (true) {
            if ((lexeme = ikSegmenter.next()) == null){
                break;
            }
            //获取分词器分词产生的词汇
            String lexemeText = lexeme.getLexemeText();
            //从redis进行匹配
            String value =  cacheFeign.get(CacheConstants.CACHE_PREFIX_DIRTY_WORDS+lexemeText);

            if (!StringUtils.isEmpty(value)){
                log.info("【策略模块-敏感词策略】执行失败，短信内容含有敏感词，敏感内容为内容为：lexemeText={}", lexemeText);
                pushMsgUtil.pushReport(standardSubmit, StrategyConstants.STRATEGY_ERROR_DIRTY_WORDS);
                pushMsgUtil.sendLog(standardSubmit, StrategyConstants.STRATEGY_ERROR_DIRTY_WORDS);
                return false;
            }
        }
        log.info("【策略模块-敏感词策略】执行成功");
        return true;
    }
}
